<template>
  <div class="history-page">
    <div class="page-title">评分历史</div>

    <!-- 搜索表单 -->
    <el-card class="search-card" shadow="never">
      <el-form
        :model="searchForm"
        inline
        class="search-form"
        @submit.prevent="handleSearch"
      >
        <el-form-item label="患者编号">
          <el-input
            v-model="searchForm.patient_code"
            placeholder="请输入患者编号"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>

        <el-form-item label="任务状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 任务列表 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="taskList"
        stripe
        class="task-table"
        empty-text="暂无数据"
      >
        <el-table-column prop="task_id" label="任务ID" width="100" align="center">
          <template #default="{ row }">
            <el-tag type="info" size="small">#{{ row.task_id }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="patient_code" label="患者编号" min-width="120" />

        <el-table-column prop="doctor_name" label="提交医生" min-width="100" />

        <el-table-column prop="department" label="科室" min-width="100" />

        <el-table-column prop="status" label="任务状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" size="small">
              {{ row.status_name }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="submit_time" label="提交时间" width="180" />

        <el-table-column prop="complete_time" label="完成时间" width="180">
          <template #default="{ row }">
            {{ row.complete_time || '-' }}
          </template>
        </el-table-column>

        <el-table-column v-if="hasScoreColumn" prop="score" label="AI评分" width="100" align="center">
          <template #default="{ row }">
            <span v-if="row.score !== null" class="score-value">
              {{ row.score }}
            </span>
            <span v-else class="no-score">-</span>
          </template>
        </el-table-column>

        <el-table-column v-if="hasSeverityColumn" prop="severity" label="严重程度" width="100" align="center">
          <template #default="{ row }">
            <el-tag
              v-if="row.severity"
              :type="getSeverityTagType(row.severity)"
              size="small"
            >
              {{ row.severity_name }}
            </el-tag>
            <span v-else class="no-score">-</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="120" align="center" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              text
              size="small"
              @click="handleViewDetail(row.task_id)"
            >
              <el-icon><View /></el-icon>
              查看结果
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current_page"
          v-model:page-size="pagination.page_size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, Refresh, View } from '@element-plus/icons-vue'
import { getTaskList } from '@/api/scoring'

const store = useStore()
const router = useRouter()

// 搜索表单数据
const searchForm = reactive({
  patient_code: '',
  status: undefined as number | undefined
})

// 状态选项
const statusOptions = [
  { label: '待处理', value: 1 },
  { label: '分析中', value: 2 },
  { label: '已完成', value: 3 },
  { label: '失败', value: 4 }
]

// 计算属性
const taskList = computed(() => store.state.scoring.taskList)
const pagination = computed(() => store.state.scoring.pagination)
const loading = computed(() => store.state.scoring.isLoading)

// 根据当前数据显示是否需要评分相关列
const hasScoreColumn = computed(() => {
  return taskList.value.some(task => task.score !== null)
})

const hasSeverityColumn = computed(() => {
  return taskList.value.some(task => task.severity !== null)
})

// 获取任务列表
const fetchTaskList = async () => {
  const params = {
    page: pagination.value.current_page,
    pageSize: pagination.value.page_size,
    patient_code: searchForm.patient_code.trim(),
    status: searchForm.status
  }

  await store.dispatch('scoring/getTaskList', params)
}

// 搜索
const handleSearch = () => {
  // 重置到第一页
  store.state.scoring.pagination.current_page = 1
  fetchTaskList()
}

// 重置搜索表单
const handleReset = () => {
  searchForm.patient_code = ''
  searchForm.status = undefined
  store.state.scoring.pagination.current_page = 1
  fetchTaskList()
}

// 查看详情
const handleViewDetail = (taskId: number) => {
  router.push(`/scoring/detail/${taskId}`)
}

// 分页大小改变
const handleSizeChange = (newSize: number) => {
  store.state.scoring.pagination.page_size = newSize
  store.state.scoring.pagination.current_page = 1
  fetchTaskList()
}

// 当前页改变
const handleCurrentChange = (newPage: number) => {
  store.state.scoring.pagination.current_page = newPage
  fetchTaskList()
}

// 获取状态标签类型
const getStatusTagType = (status: number) => {
  const typeMap = {
    1: 'info',     // 待处理
    2: 'warning',  // 分析中
    3: 'success',  // 已完成
    4: 'danger'    // 失败
  }
  return typeMap[status] || 'info'
}

// 获取严重程度标签类型
const getSeverityTagType = (severity: number) => {
  const typeMap = {
    1: 'success', // 缓解期
    2: '',        // 轻度
    3: 'warning', // 中度
    4: 'danger'   // 重度
  }
  return typeMap[severity] || 'info'
}

// 监听路由变化，重新加载数据
watch(
  () => router.currentRoute.value,
  () => {
    fetchTaskList()
  },
  { immediate: true }
)

// 页面加载时获取数据
onMounted(() => {
  fetchTaskList()
})
</script>

<style scoped>
.history-page {
  padding: 0;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 24px;
  padding-bottom: 12px;
  border-bottom: 2px solid #e0e0e0;
}

/* 搜索表单样式 */
.search-card,
.table-card {
  border-radius: 12px;
  border: 1px solid #e0e0e0;
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 24px;
}

.search-form {
  margin: 0;
}

.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 20px;
}

.search-form .el-form-item:last-child {
  margin-right: 0;
}

/* 表格样式 */
.table-card {
  margin-bottom: 0;
}

.task-table {
  width: 100%;
}

.score-value {
  font-weight: 600;
  color: #409eff;
  font-size: 16px;
}

.no-score {
  color: #c0c4cc;
  font-style: italic;
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

/* Element Plus 样式覆盖 */
:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table__header) {
  background-color: #fafafa;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

:deep(.el-table__row:hover) {
  background-color: #f0f9ff !important;
}

:deep(.el-pagination) {
  display: flex;
  align-items: center;
}

:deep(.el-pagination__sizes) {
  margin-right: 16px;
}

:deep(.el-pagination__total) {
  margin-right: 16px;
  color: #606266;
  font-weight: 500;
}

:deep(.el-tag) {
  font-weight: 500;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
  background-color: #f0f9ff;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-form .el-form-item {
    margin-bottom: 16px;
    margin-right: 0;
  }

  .search-form .el-form-item:last-child {
    margin-bottom: 0;
  }
}

@media (max-width: 768px) {
  .page-title {
    font-size: 20px;
    margin-bottom: 16px;
  }

  .search-card {
    margin-bottom: 16px;
  }

  .search-form {
    display: block;
  }

  .search-form .el-form-item {
    display: block;
    margin-bottom: 16px;
    margin-right: 0;
  }

  .search-form .el-form-item:last-child {
    margin-bottom: 0;
  }

  .search-form .el-input,
  .search-form .el-select {
    width: 100% !important;
  }

  .search-form .el-button {
    width: 48%;
  }

  :deep(.el-table) {
    font-size: 12px;
  }

  .pagination-container {
    justify-content: flex-start;
    overflow-x: auto;
  }

  :deep(.el-pagination) {
    min-width: 600px;
  }
}

/* 空状态样式 */
:deep(.el-table__empty-text) {
  color: #909399;
  font-size: 14px;
}

:deep(.el-table__empty-block) {
  min-height: 200px;
}
</style>